<template>
  <t-dialog v-model:visible="visible" attach="body" header="选择赠品" width="70%" >
    <custom-search ref="customSearchRef" v-slot="{ params }"
      :default-params="{ actualEndTime: [], actualBeginTime: [] }" @submit="handleInitTable">
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table 
      ref="customTableRef" 
      row-key="id" 
      :columns="columns" 
      :api="GiftProjectListCRUD.page"
      column-controller-key="GiftProjectList"
      :selected-row-keys="selectedRowKeys"
      @select-change="handleSelectChange"
      :on-before-set-data="handleTableSetData"
      >
      

      <template #fileUrl="{ row }">
        <image-viewer v-if="row.fileUrl" :images="[row.fileUrl]" width="80px" height="80px" />
      </template>
   
    
      <template #status="{ row }">
        <t-switch
          v-model:value="row.status"
          :custom-value="['0', '1']"
          :loading="row.loading"
          @change="handleChangeStatus(row)"
        />
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      

    </custom-table>

      
    <template #footer>
      <t-button theme="default" @click="visible = false">取消</t-button>
      <t-button theme="warning" @click="handleReset">重置</t-button>
      <t-button :loading="loadingSubmit" @click="handleSelectedIds">保存</t-button>
    </template>
  </t-dialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue';
import { MessagePlugin, TableCol, TreeNodeModel } from 'tdesign-vue-next';
import ImageViewer from '@/components/image-viewer/index.vue';
import { GiftProjectListCRUD } from '@/api/budget/gift-project';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import { useDictionaryStore } from '@/store';

const dictionaryStore = useDictionaryStore();

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  single: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(['update:visible', 'save']);

const visible = ref(props.visible);
const selectedId = ref();
const selectedRowKeys = ref([]);
const selectedRows = ref(null);
const loadingSubmit = ref(false);

// 处理改变默认配置
const handleChangeStatus = (row: Record<string, any>) => {
  row.loading = true;
  const params = { ...row };
  GiftProjectListCRUD
    .update(params)
    .then(() => {
      MessagePlugin.success('编辑成功');
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    .finally(() => {
      row.loading = false;
      handleRefreshTable();
    });
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};

// columns
const columns = computed<TableCol[]>(() =>[
  { colKey: 'row-select', type: props.single ? 'single' : 'multiple', width: 64, fixed: 'left' },
  { colKey: 'name', title: '赠品名称', width: 100 },
  { colKey: 'fileUrl', title: '赠品图片', width: 300 },
  { colKey: 'money', title: '赠品价值金额', width: 250 },
  { colKey: 'remark', title: '备注' },
  { colKey: 'status', title: '是否启用', width: 100 },
  { colKey: 'createTime', title: '创建时间', width: 180 },
]);


// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');

const handleSelectChange = (keys: any[], rows: any[]) => {
  selectedRowKeys.value = keys;
  selectedRows.value = rows;
};

const handleInitTable = () => {
  const params = {
    ...customSearchRef.value.params,
  };
  customTableRef.value.initTable(params);
};
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  return data
};

const handleReset = () => {
  selectedRowKeys.value = [];
  selectedRows.value = null;
  customSearchRef.value.reset(); // 重置搜索条件
};
// 选择传递
const handleSelectedIds = (row:any) => {
  if (selectedRows.value.selectedRowData.length === 0) {
    MessagePlugin.warning('请先选择数据');
    return;
  }

  const selectedData = selectedRows.value.selectedRowData.map((row: any) => {
    const { id, ...rest } = row; // 使用解构赋值将 `id` 从 `row` 中提取出来，剩下的属性放在 `rest` 中
    return {
      ...rest, // 展开 `rest`，包含除了 `id` 之外的所有属性
      projectName: row.name,
      giftId: row.id, // 将 `row.id` 赋值给 `giftId`
      materialsId: row.id,
    };
  });
  emits('save', selectedData);
  visible.value = false;
};

watch(
  () => props.visible,
  async (newVal) => {
    visible.value = newVal;
    if(newVal==true) {
      await handleInitTable();
      handleReset();

    
    }
  }
);

watch(visible, (newVal) => {
  emits('update:visible', newVal);
});

</script>

<style lang="less" scoped>
:deep(.t-radio-group .t-radio-button) {
  border: none;
  border-radius: 18px !important;
  margin-left: 11px;
}

:deep(.t-radio-group .t-radio-button.t-is-checked) {
  background-color: #f2f3f5;
}
</style>